import {GAME_CONFIGS} from "./GameConfigs";
import {md5} from "../../utils/md5";
import {M} from "./MatchAdapter";
import {userProfile} from "../../entity/UserProfile";

/**
 * 用于Matchvs 第三方绑定接口。
 */
export class MatchvsBind {

    public getSign(params): string {
        let str = GAME_CONFIGS.appkey + "&" + params + "&" + GAME_CONFIGS.secret;
        console.log(str);
        let md5Str = md5(str);
        console.log(md5Str);
        return md5Str;
    }

    public getBindOpenIDAddr(): string {
        const channel = GAME_CONFIGS.channel;
        const platform = GAME_CONFIGS.platform;
        if (channel === "MatchVS" || channel === "Matchvs") {
            if (platform === "release") {
                return "https://vsuser.matchvs.com/wc6/thirdBind.do?"
            } else if (platform === "alpha") {
                return "http://alphavsuser.matchvs.com/wc6/thirdBind.do?";
            }
        }
    }

    public bindOpenIDWithUserID() {
        console.log('openid:' + userProfile.openid);
        if (!userProfile.openid) {
            console.warn("没有获取到微信OpenID，获取OpenID请参考：" + 'http://www.matchvs.com/service?page=third');
            M.registerUser();
            return;
        }

        let req = new XMLHttpRequest();
        let reqUrl = this.getBindOpenIDAddr();
        req.open("post", reqUrl, true);
        req.setRequestHeader("Content-Type", "application/json");
        req.onreadystatechange = () => {
            if (req.readyState === 4 && (req.status >= 200 && req.status < 400)) {
                try {
                    let response = req.responseText;
                    let data = JSON.parse(response).data;
                    console.log("绑定结果1", data.userid, data.token);
                    userProfile.updateThirdInfo(data);
                    // console.log("三方绑定数据:", userProfile, userProfile.thirdInfo);
                    M.login();
                } catch (error) {
                    console.warn(error.message);
                    M.registerUser();
                }
            }
        };
        let params = "gameID=" + GAME_CONFIGS.gameId + "&openID=" + userProfile.openid + "&session=" + userProfile.token + "&thirdFlag=2";
        //计算签名
        let signstr = this.getSign(params);
        let jsonParam = {
            userID: 0,
            gameID: GAME_CONFIGS.gameId,
            openID: userProfile.openid,
            session: userProfile.token,
            thirdFlag: 2,
            sign: signstr
        };
        req.send(JSON.stringify(jsonParam));
    }
}